//
//  LAXImagePickerControllerViewController.swift
//  MeiLiTV
//
//  Created by 冰凉的枷锁 on 2017/3/31.
//  Copyright © 2017年 冰凉的枷锁. All rights reserved.
//

import UIKit

class LAXImagePickerController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    var imagePickerController = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        imagePickerController.modalTransitionStyle = .flipHorizontal
        imagePickerController.allowsEditing = true
    }
    
    private func showCamera() {//UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerController.sourceType = .camera
            self.show(imagePickerController, sender: nil)
        } else {
            let vc = LAXAlertView.alertViewWarning(message: "没有检测到摄像头")
            self.show(vc, sender: nil)
        }
    }
    
    private func showPhotoLibrary() {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            imagePickerController.sourceType = .photoLibrary
            imagePickerController.delegate = self
            self.show(imagePickerController, sender: nil)
        } else {
            let vc = LAXAlertView.alertViewWarning(message: "不能打开相册")
            self.show(vc, sender: nil)
        }
    }
    
    func showImagePickerController() {
        let sheet = UIAlertController.init(title: "请选择", message: nil, preferredStyle: .actionSheet)
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        let camera = UIAlertAction.init(title: "拍照", style: .default) {(alert) in
            self.showCamera()
        }
        let photo = UIAlertAction.init(title: "相册", style: .default) {(alert) in
            self.showPhotoLibrary()
        }
        sheet.addAction(camera)
        sheet.addAction(photo)
        sheet.addAction(cancel)
        self.show(sheet, sender: nil)
    }
    
    //保存图片至沙盒
    func saveImage(currentImage: UIImage, newSize: CGSize, percent: CGFloat, imageName: String){
        //压缩图片尺寸
        UIGraphicsBeginImageContext(newSize)
        currentImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            //UIImageJPEGRepresentation此方法可将图片压缩，但是图片质量基本不变，第二个参数即图片质量参数。
            if let imageData = UIImageJPEGRepresentation(newImage, percent) as NSData? {
                let fullPath = NSHomeDirectory().appending("/Documents")
                imageData.write(toFile: fullPath, atomically: false)
            }
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        self.dismiss(animated: true, completion: nil)
    }
    /*
    //实现点击图片预览功能，滑动放大缩小，带动画
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.isFullScreen = !self.isFullScreen
        
        let touch: UITouch = touches.first as! UITouch
        let touchPoint: CGPoint  = touch.locationInView(self.view)
        let imagePoint: CGPoint = self.imageView.frame.origin
        //touchPoint.x ，touchPoint.y 就是触点的坐标
        // 触点在imageView内，点击imageView时 放大,再次点击时缩小
        if(imagePoint.x <= touchPoint.x && imagePoint.x + self.imageView.frame.size.width >= touchPoint.x && imagePoint.y <=  touchPoint.y && imagePoint.y+self.imageView.frame.size.height >= touchPoint.y){
            // 设置图片放大动画
            UIView.beginAnimations(nil, context: nil)
            // 动画时间
            UIView.setAnimationDuration(1)
            
            if (isFullScreen) {
                // 放大尺寸
                self.imageView.frame = CGRectMake(0, 0, 480, 320)
            }
            else {
                // 缩小尺寸
                self.imageView.frame = CGRectMake(100, 100, 128, 128)
                174             }
            // commit动画
            UIView.commitAnimations()
        }
    }
    
    //MARK:- UIImagePickerControllerDelegate
    func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){
        
        //picker.dismiss(animated: true, completion: nil)
        var image: UIImage?
        
        if(picker.allowsEditing){
            //裁剪后图片
            image = info[UIImagePickerControllerEditedImage] as? UIImage
        }else{
            //原始图片
            image = info[UIImagePickerControllerOriginalImage] as? UIImage
        }
        if image != nil {
            saveImage(currentImage: image!, newSize: CGSize.init(width: 256, height: 256), percent: 0.5, imageName: "newimage.png")
            print(NSHomeDirectory().appending("/Documents").appending("/currentImage.png"))
        }
        /* 此处info 有六个值
         114         * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
         115         * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
         116         * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
         117         * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
         118         * UIImagePickerControllerMediaURL;       // an NSURL
         119         * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
         120         * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
         121         */
        // 保存图片至本地，方法见下文
//        self.saveImage(currentImage: image, newSize: CGSize(width: 256, height: 256), percent: 0.5, imageName: "currentImage.png")
//        let fullPath: String = NSHomeDirectory().appending("/Documents").appending("/currentImage.png")
//        print("fullPath=\(fullPath)")
//        let savedImage: UIImage = UIImage(contentsOfFile: fullPath)!
//        self.isFullScreen = false
//        self.imageView.image = savedImage
        //在这里调用网络通讯方法，上传头像至服务器...
    }*/
    
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
    
}
